<template>
    <div class="image-preview">
        <img alt="北京华锐云空间" :src="props.src" ref="imgRef" :style="imgStyle" />
    </div>

    <Teleport :to="'body'">
        <img class="image-preview-img" :src="props.src" @click="onPreviewClick" :style="imgPreviewStyle"
            v-if="isShowPreview" />
    </Teleport>

    <Teleport to="body">
        <div class="image-preview-mask" @click="onPreviewClick" v-if="isShowMask"></div>
    </Teleport>
</template>
<script setup>
import { nextTick, ref } from "vue";
const props = defineProps({
    src: {
        type: String,
        default: "",
    },
});
const imgRef = ref(null);
const imgStyle = ref({});
const imgPreviewStyle = ref({});
const isShowMask = ref(false);
const isShowPreview = ref(false);
const ms = 800;

const onPreviewClick = () => {
    const { left, top, width, height } = imgRef.value.getBoundingClientRect();
    imgPreviewStyle.value = {
        position: "fixed",
        left: `${left}px`,
        top: `${top}px`,
        width: `${width}px`,
        height: `${height}px`,
        zIndex: 1001,
        transition: `all ${ms}ms`,
    };
    setTimeout(() => {
        imgStyle.value = {};
        isShowMask.value = false;
        isShowPreview.value = false;
    }, ms);
};

const onClick = async () => {
    isShowPreview.value = true;
    const w = window.innerWidth;
    const h = window.innerHeight;
    const { left, top, width, height } = imgRef.value.getBoundingClientRect();
    const scaleWidth = window.innerWidth * 0.8;
    const scaleHeight = (height * scaleWidth) / width;

    imgPreviewStyle.value = {
        position: "fixed",
        left: `${left}px`,
        top: `${top}px`,
        width: `${width}px`,
        height: `${height}px`,
        zIndex: 1001,
    };

    await nextTick();

    setTimeout(() => {
        isShowMask.value = true;
        imgStyle.value = {
            visibility: "hidden",
        };
        imgPreviewStyle.value = {
            position: "fixed",
            left: `${(w - scaleWidth) / 2}px`,
            top: `${(h - scaleHeight) / 2}px`,
            width: `${scaleWidth}px`,
            height: `${scaleHeight}px`,
            transition: `all ${ms}ms`,
            zIndex: 1001,
        };
    }, 200);
};
</script>
<style lang="scss">
.image-preview-img {
    background-color: #fff;
}
</style>
<style lang="scss" scoped>
.image-preview-mask {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
}

.image-preview {
    width: 100%;
    height: 100%;

    img {
        width: 100%;
        background-color: #fff;
    }
}
</style>
